package com.lagou.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lagou.register.ICompleteCallback;
import com.lagou.rpc.RpcRequest;
import com.lagou.rpc.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

public final class ClientHandler extends ChannelInboundHandlerAdapter /*implements Callable*/ {

    private ChannelHandlerContext context;
    private RpcResponse result;
    //private RpcRequest para;
    private ICompleteCallback callback;


    public void channelActive(ChannelHandlerContext ctx) {
        context = ctx;
    }

    /**
     * 收到服务端数据，唤醒等待线程
     */

    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
        result = (RpcResponse) msg;
        if (null != callback)
            callback.call(result);

        notify();
    }

    /**
     * 阻塞方式
     */
    public synchronized Object waitThenCallback() throws InterruptedException {
        wait();
        return result;
    }

    /**
     * 注册异步回调
     */
    public void asyncCallback(ICompleteCallback callback) throws InterruptedException {
        this.callback = callback;
    }


    /**
     * 写出数据，开始等待唤醒
     */

    /*public synchronized Object call() throws InterruptedException {
        context.writeAndFlush(para);
        wait();
        System.out.println("-------------------------\n 返回报文: \n"
                + JSON.toJSONString(result, SerializerFeature.PrettyFormat));
        return result.getResult();
    }*/


    /*void setPara(RpcRequest para) {
        this.para = para;
    }*/

}
